package com.elitel.frame.web.serverinfocustom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.elitel.common.utils.SysUserUtils;
import com.elitel.frame.web.cfgsiminfo.dao.CfgSimInfoDao;
import com.elitel.frame.web.cfgsiminfo.dao.CfgSimQueryFieldDao;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimInfo;
import com.elitel.frame.web.cfgsiminfo.entity.CfgSimQueryField;
import com.elitel.frame.web.common.idworker.IdWorker;
import com.elitel.frame.web.serverinfo.dto.ServerConfigDTO;
import com.elitel.frame.web.serverinfo.dto.ServerInfoDTO;
import com.elitel.frame.web.serverinfo.dto.ServerQueryFieldDTO;
import com.elitel.frame.web.serverinfocustom.dto.SimServerInfoDTO;
import com.elitel.frame.web.serverinfocustom.service.SererInfoCustomService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author m
 */
@Service
public class SimServerInfoService implements SererInfoCustomService {


    @Resource
    private CfgSimInfoDao cfgSimInfoDao;

    @Resource
    private CfgSimQueryFieldDao cfgSimQueryFieldDao;


    @Override
    public void save(ServerInfoDTO dto) {
        // 保存基本信息
        CfgSimInfo simInfo = this.getCfgSimInfo(dto);
        CfgSimInfo dbSim = cfgSimInfoDao.selectByServerId(simInfo.getServiceId());
        if (dbSim == null) {
            simInfo.setCreatedTime(new Date());
            simInfo.setCreatedUser(SysUserUtils.getLoginAccount());
            simInfo.setUpdatedTime(new Date());
            simInfo.setUpdatedUser(SysUserUtils.getLoginAccount());
            cfgSimInfoDao.insert(simInfo);
        } else {
            simInfo.setUpdatedTime(new Date());
            simInfo.setUpdatedUser(SysUserUtils.getLoginAccount());
            cfgSimInfoDao.updateByServerIdSelective(simInfo);
        }
        // 保存参数信息
        List<CfgSimQueryField> cfgSimQueryFieldList = this.getCfgSimQueryFieldList(dto);
        cfgSimQueryFieldDao.deleteByServiceId(simInfo.getServiceId());
        if (CollectionUtils.isNotEmpty(cfgSimQueryFieldList)) {
            cfgSimQueryFieldDao.insertBatch(cfgSimQueryFieldList);
        }
    }

    private List<CfgSimQueryField> getCfgSimQueryFieldList(ServerInfoDTO dto) {
        List<ServerQueryFieldDTO> queryFieldList = dto.getQueryFieldList();
        String serverId = dto.getBasicConfig().getServerId();
        ArrayList<CfgSimQueryField> resList = new ArrayList<>();
        int size = queryFieldList.size();
        for (int i = 0; i < size; i++) {
            ServerQueryFieldDTO item = queryFieldList.get(i);
            CfgSimQueryField res = new CfgSimQueryField();
            res.setQueryFieldId(IdWorker.createStrId());
            res.setServiceId(serverId);
            res.setSourceFieldCode(item.getMetaFieldCode());
            res.setSourceFieldName(item.getMetaFieldCode());
            res.setNewFieldCode(item.getFieldCode());
            res.setNewFieldName(item.getFieldName());
            res.setParamType(Integer.valueOf(item.getExt1()));
            res.setDefaultValue(item.getFieldDefaultValue());
            res.setSortNum(i + 1);
            res.setCreatedTime(new Date());
            res.setUpdatedTime(new Date());
            res.setCreatedUser(SysUserUtils.getLoginAccount());
            res.setUpdatedUser(SysUserUtils.getLoginAccount());
            resList.add(res);
        }
        return resList;
    }

    private CfgSimInfo getCfgSimInfo(ServerInfoDTO dto) {
        SimServerInfoDTO successor = dto.getSuccessor(SimServerInfoDTO.class);
        ServerConfigDTO basicConfig = dto.getBasicConfig();
        CfgSimInfo simInfo = new CfgSimInfo();
        simInfo.setInfoId(basicConfig.getServerId());
        simInfo.setServiceId(basicConfig.getServerId());
        // 先置空
        simInfo.setRequestHeader("{}");
        List<ServerQueryFieldDTO> queryFields = successor.getQueryFieldList();
        if (CollectionUtils.isNotEmpty(queryFields)) {
            List<ServerQueryFieldDTO> headerList = queryFields.stream().filter(queryField -> "2".equals(queryField.getExt1())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(headerList)) {
                HashMap<String, String> headerMap = new HashMap<>();
                for (ServerQueryFieldDTO header : headerList) {
                    headerMap.put(header.getFieldCode(), header.getFieldDefaultValue());
                }
                simInfo.setRequestHeader(JSONObject.toJSONString(headerMap));
            }
        }
        simInfo.setRequestMethod(successor.getRequestMethod());
        simInfo.setRequestUrl(successor.getRequestUrl());
        simInfo.setContentType(successor.getContentType());
        // 二期把参数类型去掉了, 暂时先用R
        simInfo.setOptType("R");
        simInfo.setSimType(successor.getSimType());
        simInfo.setRemark(successor.getRemark());
        return simInfo;
    }

    /**
     * 根据id查询服务自定义配置信息
     *
     * @param serverId
     * @return
     */
    @Override
    public Map<String, Object> selectByServerId(String serverId) {
        CfgSimInfo simInfo = cfgSimInfoDao.selectByServerId(serverId);
        HashMap<String, Object> resMap = new HashMap<>();
        if (simInfo != null) {
            resMap.put("requestMethod", simInfo.getRequestMethod());
            resMap.put("requestUrl", simInfo.getRequestUrl());
            resMap.put("contentType", simInfo.getContentType());
            resMap.put("simType", simInfo.getSimType());
            resMap.put("remark", simInfo.getRemark());
        }
        return resMap;
    }
}
